import React, { Component } from 'react';
import { message } from 'antd';
import { customAlphabet } from 'nanoid/non-secure';
import { formatMessage } from 'umi-plugin-react/locale';

function inject_unount(target) {
  // 改装componentWillUnmount，销毁的时候记录一下
  let next = target.prototype.componentWillUnmount;
  target.prototype.componentWillUnmount = function () {
    if (next) next.call(this, ...arguments);
    this.unmount = true;
  };
  // 对setState的改装，setState查看目前是否已经销毁
  let setState = target.prototype.setState;
  target.prototype.setState = function () {
    if (this.unmount) return;
    setState.call(this, ...arguments);
  };
}

@inject_unount
class BaseComponent extends Component {
  /**
   * 图片类文件上传前的验证
   */
  simpleBeforeImageFileUpload = (file, fileList) => {
    // 格式效验
    const { type } = file;
    if (type != 'image/jpeg' && type != 'image/png') {
      file.status = 'error';
      file.response = formatMessage({ id: 'app.iesx.exhibition.step5.upload.error4' });
      return false;
    }
  };

  /**
   * 获取包装后的数据
   * @param {*} msg
   * @returns
   */
  getPackMessage(msg) {
    return <span style={{ color: '#333', fontSize: '15px', fontWeight: '600' }}>{msg}</span>;
  }

  /**
   * 显示成功信息
   * @param {*} msg
   */
  successMessage = (msg = '') => {
    const str = this.getPackMessage(msg);
    message.success(str);
  };

  /**
   * 显示loading消息
   * @param {*} msg
   * @param {*} duration
   * @returns
   */
  loadingMessage = (msg = '', duration = 0) => {
    const str = this.getPackMessage(msg);
    const hide = message.loading(str, duration);
    return hide;
  };

  /**
   * 显示错误信息
   * @param {*} msg
   */
  errorMessage = (msg = '') => {
    const bo = React.isValidElement(msg);
    if (bo) {
      message.error(msg);
    } else {
      const str = this.getPackMessage(msg);
      message.error(str);
    }
  };

  /**
   * 执行http的get请求
   * @param {*} url
   * @param {*} payload
   * @returns
   */
  execHttp = (url, payload) => {
    const { dispatch } = this.props;

    return new Promise((resolve, reject) => {
      dispatch({
        type: url,
        payload: { ...payload }
      })
        .then(res => {
          resolve(res);
        })
        .catch(reason => {
          reject(reason);
        });
    });
  };

  /**
   * 执行Reducer操作
   * @param {*} url
   * @param {*} payload
   */
  runReducer = (url, payload) => {
    const { dispatch } = this.props;
    dispatch({
      type: url,
      payload: {
        ...payload,
      },
    });
  };

  /**
   * 转换对象为json格式,并打印
   * @param obj
   */
  printJson = obj => {
    if (obj) {
      console.log(JSON.stringify(obj));
    }
  };

  /**
   * 打印日志
   * @param obj
   */
  printLog = obj => {
    console.log(`%c${JSON.stringify(obj)}`, 'color: yellow;');
  };

  /**
   * 生成唯一id
   * @returns {string}
   */
  generateId = () => {
    const nanoid = customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 8);
    const id = nanoid();
    return id;
  };

  /**
   * 根据给定的按钮的Tags,获取可以显示的按钮的个数
   * @param tags
   */
  getVisibleBtnCount = ({ tags }) => {
    let sum = 0;
    const hiddenMenuButton = localStorage.getItem('cancersystem_menubutton');
    for (let i = 0; i < tags.length; i++) {
      const tag = tags[i];
      if (hiddenMenuButton.indexOf(tag) == -1) {
        sum++;
      }
    }
    return sum;
  };

  /**
   * 睡眠
   * @param time
   * @returns {Promise<unknown>}
   */
  sleep = time => {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, time);
    });
  };

  /**
   * 检查当前用户是否为管理员或者超级管理员
   * @param currentUser
   */
  checkIsAdmin = currentUser => {
    const { orgName = '', roles: currentRoles, regions } = this.props.currentUser;
    // 检查是否包含ROLE_ADMIN
    const isAdmin = currentRoles
      ? currentRoles.some(item => item === 'ROLE_ADMIN' || regions.length < 3)
      : false;
    return isAdmin;
  };

  /**
   * 检查当前用户是否为管理员角色
   * @param currentUser
   * @returns {*|boolean}
   */
  checkIsManager = currentUser => {
    const { orgName = '', roles: currentRoles } = this.props.currentUser;
    // 检查是否包含ROLE_ADMIN
    const isAdmin = currentRoles ? currentRoles.some(item => item === 'ROLE_MANAGER') : false;
    return isAdmin;
  };
}

export default BaseComponent;
